package com.six.controller;

import com.six.service.RedisService;
import com.six.util.CaptchaUtil;
import com.six.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("captcha")
@CrossOrigin
public class CaptchaController {

    @Autowired
    CaptchaUtil captchaUtil;
    @Autowired
    RedisService redisService;
    @RequestMapping("base")
    public Result getCaptcha(HttpServletResponse response){
        String[] arr=captchaUtil.getImage();
        String key=arr[0];
        String base64=arr[1];

        return Result.success("已经更新验证码",key+"+data:image/jpeg;base64,"+base64);
    }
    @RequestMapping("check")
    public Result checkCaptcha(HttpServletRequest request,@RequestParam("captchaCode") String captchaCode){
        Cookie[] cookies=request.getCookies();
        String key=null;
        for(Cookie cookie:cookies ){
            if(cookie.getName().equals("captchakey")){
                key=cookie.getValue();
                break;
            }
        }
        if(key== null){
            return Result.fail(400,"请求参数异常");
        }
        String code=(String)redisService.get(key);
        if(code==null) {
            return Result.fail(201, "验证码已过期");
        }
        if(captchaCode.equalsIgnoreCase(code)){
            return Result.success("验证码正确",true);
        }
        return Result.fail(400,"验证错误");

    }
}
